#include "core.h"
#include "xTime.h"
#include "Misc.h"

#if defined(_WIN32)
#include <windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif

#ifdef _WIN32
static LARGE_INTEGER yo;
#else
static timeval tp, initialTime;
#endif

xTime xTime::x;

S64 xTime::getTime( void )
{
#ifdef _WIN32
	LARGE_INTEGER PerfVal;

	QueryPerformanceCounter( &PerfVal );

	return (S64)(PerfVal.QuadPart*1000 / yo.QuadPart);
#else
	gettimeofday( &tp, 0 );

	// Seconds to ms and microseconds to ms
	return ( tp.tv_sec - initialTime.tv_sec ) * 1000 + ( tp.tv_usec - initialTime.tv_usec ) / 1000;

#endif
}

std::string xTime::getTimeStr()
{
	time_t t = time(NULL);
	std::string str;
	CMisc::ToString((U8*)&t, sizeof(t), str);
	return str;
}

S64 xTime::getTimeNs( void )
{
#ifdef _WIN32
	LARGE_INTEGER PerfVal;

	QueryPerformanceCounter( &PerfVal );

	__int64 quotient, remainder;
	quotient=((PerfVal.QuadPart*1000) / yo.QuadPart);
	remainder=((PerfVal.QuadPart*1000) % yo.QuadPart);
	//return (PerfVal.QuadPart*1000 / (yo.QuadPart/1000));
	return quotient*1000 + (remainder*1000 / yo.QuadPart);

#else
	gettimeofday( &tp, 0 );

	return ( tp.tv_sec - initialTime.tv_sec ) * 1000000 + ( tp.tv_usec - initialTime.tv_usec );

#endif
}

xTime::xTime(void)
{
#ifdef _WIN32
	QueryPerformanceFrequency( &yo );
	// The original code shifted right 10 bits
	//counts = yo.QuadPart >> 10;
	// It gives the wrong value since 2^10 is not 1000
	//	counts = yo.QuadPart;// / 1000;
#else
	gettimeofday( &initialTime, 0 );
#endif
}

xTime::~xTime(void)
{
}